<template>
  <div class="app-container">
    <div class="control-panel">
      <el-button @click="toggleAnnotationMode">{{ isAnnotating ? '🛑 结束标注' : '📌 开始标注' }}</el-button>
      <el-button id="saveBtn">💾 保存当前线路</el-button>

      <!-- 路线选择 -->
      <el-button id="loadRouteBtn">🔍 加载路线</el-button>

      <el-button id="clearBtn">🗑️ 清除所有线路</el-button>
      <el-button @click="resetView">🔄 还原视图</el-button>
      <span class="status">{{ statusText }}</span>
    </div>
    <el-row :gutter="20">
      <el-col :span="4">
        <div>
          <h1>线路列表</h1>
<!--          <div v-for="line in lines">{{ line.id + ":" + line.name }}</div>-->

          <el-card shadow="hover"  v-for=" switchItem in switchAndLineList ">
            <div slot="header" class="clearfix">
              <span>{{ switchItem.switchInfo ? switchItem.switchInfo.switchName : "未配置开关"}}</span>
              <el-button style="float: right; padding: 3px 0" type="text">action</el-button>
            </div>
            <div  v-if="switchItem.lineList == null">
              暂无
            </div>
            <div v-else>
              <div v-for="lineItem in switchItem.lineList" :key={lineItem} class="text item">
                {{lineItem.lineName}}
                <el-divider></el-divider>
              </div>
            </div>

          </el-card>
        </div>
      </el-col>
      <el-col :span="20">
        <div id="container" ref="container">
          <svg id="svg-container" ref="svg_container" xmlns="http://www.w3.org/2000/svg"
               style="width: 33.1102in;height: 23.3858in;"  viewBox="0 0 2383.94 1683.78" :style="{
          transform: `translate(${viewState.x}px, ${viewState.y}px) scale(${viewState.scale})`,
          cursor: svgCursor
        }">
            <image id="background" :href="drawingUrl" width="100%" preserveAspectRatio="xMidYMid meet"></image>

          </svg>
        </div>
      </el-col>
    </el-row>


    <el-dialog
      title="完善线路信息"
      :visible.sync="lineInfoDialogVisible"
      width="30%"
    >
      <el-form ref="lineForm" :model="lineForm" :rules="lineFromRules" label-width="80px">
        <el-form-item label="部门id" prop="deptId">
          <el-input v-model="lineForm.deptId" placeholder="请输入部门id" />
        </el-form-item>
        <el-form-item label="图纸ID" prop="drawingId">
          <el-input v-model="lineForm.drawingId" placeholder="请输入图纸ID" />
        </el-form-item>
        <el-form-item label="接触网开关器ID" prop="catenarySwitchId">
<!--          <el-input v-model="lineForm.catenarySwitchId" placeholder="请输入接触网开关器ID" />-->
          <el-select v-model="lineForm.catenarySwitchId" placeholder="请选择接触网开关器" clearable>
            <el-option key="-1" label="不分配开关" value="-1"></el-option>
            <el-option
              v-for="item in switchList"
              :key="item.id"
              :label="item.switchName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="线名称" prop="lineName">
          <el-input v-model="lineForm.lineName" placeholder="请输入线名称" />
        </el-form-item>
        <el-form-item label="线code" prop="lineCode">
          <el-input v-model="lineForm.lineCode" placeholder="请输入线code" />
        </el-form-item>
        <el-form-item label="x1" prop="x1">
          <el-input v-model="lineForm.x1" placeholder="请输入x1" />
        </el-form-item>
        <el-form-item label="y1" prop="y1">
          <el-input v-model="lineForm.y1" placeholder="请输入y1" />
        </el-form-item>
        <el-form-item label="x2" prop="x2">
          <el-input v-model="lineForm.x2" placeholder="请输入x2" />
        </el-form-item>
        <el-form-item label="y2" prop="y2">
          <el-input v-model="lineForm.y2" placeholder="请输入y2" />
        </el-form-item>
        <el-form-item label="线类型" prop="lineType">
          <el-select v-model="lineForm.lineType" placeholder="请选择线类型">
            <el-option
              v-for="dict in dict.type.biz_line_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否可放置火车" prop="isTrainPlaceable">
          <el-radio-group v-model="lineForm.isTrainPlaceable">
            <el-radio
              v-for="dict in dict.type.biz_t_f"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标准参数" prop="standardParams">
          <el-input v-model="lineForm.standardParams" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="自定义参数" prop="customParams">
          <el-input v-model="lineForm.customParams" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="扩展信息" prop="ext">
          <el-input v-model="lineForm.ext" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitLineForm">确 定</el-button>
        <el-button @click="cancelLineForm">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getStation_drawingByUser } from "@/api/system/station_drawing"
import {
  addSingle_line_annotation,
  getLinesByDrawingId,
  updateSingle_line_annotation
} from "@/api/system/single_line_annotation"
import { getCatenary_switchByDrawingId,getCatenary_switchAndLinesByDrawingId }  from "@/api/system/catenary_switch"


export default {
  name: "line_annotation",
  dicts: ['biz_line_type', 'biz_t_f'],
  data() {
    return {
      // 遮罩层
      loading: true,
      lineInfoDialogVisible: false,
      //
      drawingInfo:{},
      // 表单参数
      lineForm: {},
      // 表单校验
      lineFromRules: {
        createBy: [
          { required: true, message: "创建者不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateBy: [
          { required: true, message: "更新者不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "部门id不能为空", trigger: "blur" }
        ],
        drawingId: [
          { required: true, message: "图纸ID不能为空", trigger: "blur" }
        ],
        catenarySwitchId: [
          { required: true, message: "接触网开关器ID不能为空", trigger: "blur" }
        ],
        lineName: [
          { required: true, message: "线名称不能为空", trigger: "blur" }
        ],
        lineCode: [
          { required: true, message: "线code不能为空", trigger: "blur" }
        ],
        x1: [
          { required: true, message: "x1不能为空", trigger: "blur" }
        ],
        y1: [
          { required: true, message: "y1不能为空", trigger: "blur" }
        ],
        x2: [
          { required: true, message: "x2不能为空", trigger: "blur" }
        ],
        y2: [
          { required: true, message: "y2不能为空", trigger: "blur" }
        ],
        lineType: [
          { required: true, message: "线类型不能为空", trigger: "change" }
        ],
        isTrainPlaceable: [
          { required: true, message: "是否可放置火车不能为空", trigger: "change" }
        ],
      },
      statusText: '就绪',
      svgCursor: '',
      // drawingUrl: process.env.VUE_APP_BASE_API + '/profile/drawing/demo.svg',
      drawingUrl:'',
      viewState: {x: 0, y: 0, scale: 1},
      isDragging: false,
      lastX: 0,
      lastY: 0,
      isAnnotating: false,
      tempLine: null,
      startPoint: null,
      lines: [
      ],
      switchAndLineList:[],
      switchList:[]
    }
  },
  computed: {
    container() {
      return this.$refs.container
    },
    svgContainer() {
      return this.$refs.svg_container
    }

  },
  mounted() {
    this.container.addEventListener('wheel', this.containerWheel, true);
    this.svgContainer.addEventListener('mousedown', this.svgContainerMousedown, true);
    document.addEventListener('mousemove', (e) => {
      if (!this.isDragging) return;
      this.viewState.x = e.clientX - this.lastX;
      this.viewState.y = e.clientY - this.lastY;
    });
    document.addEventListener('mouseup', () => {
      this.isDragging = false;
      this.svgCursor = this.svgCursor ? 'crosshair' : 'grab';
    });
  },
  beforeMount() {
    // window.addEventListener('resize', this.updateTransform)
  },
  beforeDestroy() {
    // window.removeEventListener('resize', this.updateTransform)
  },
  created() {
    this.initData();
  },
  methods: {
    // 初始化数据 获取站点图纸
    initData(){
      getStation_drawingByUser().then(response => {
        if(response?.data && response.data.length >=1){
          this.drawingUrl = process.env.VUE_APP_BASE_API + response.data[0].basicDrawingInfo;
          this.drawingInfo = response.data[0];
          this.getSwitchAndLineList();
          this.getSwitchList();
        }

      })
    },
    getLines(drawingId){
      getLinesByDrawingId(drawingId).then(response => {
        console.log(response);
        if(response?.data){
          this.lines = response.data;
        }
      })
    },
    getSwitchList(){
      getCatenary_switchByDrawingId(this.drawingInfo.id).then(response => {
        console.log(response);
        if(response?.data){
          this.switchList = response.data;
        }
      })
    },
    getSwitchAndLineList(){
      getCatenary_switchAndLinesByDrawingId(this.drawingInfo.id).then(response => {
        console.log(response);
        if(response?.data){
          this.switchAndLineList = response.data;
        }
      })
    },
    // ========== 坐标转换：屏幕 -> SVG ==========
    screenToSvg(clientX, clientY) {
      const pt = this.svgContainer.createSVGPoint();
      pt.x = clientX;
      pt.y = clientY;
      const svgP = pt.matrixTransform(this.svgContainer.getScreenCTM().inverse());
      return {x: svgP.x, y: svgP.y};
    },
    // ========== 创建线路元素（支持颜色）==========
    createLineElement(id, x1, y1, x2, y2, color = 'red', isTemp = false) {
      const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
      line.setAttribute('id', id);
      line.setAttribute('x1', x1);
      line.setAttribute('y1', y1);
      line.setAttribute('x2', x2);
      line.setAttribute('y2', y2);
      line.classList.add('line');

      if (isTemp) {
        line.classList.add('temp');
        line.setAttribute('stroke', 'blue');
      } else {
        line.setAttribute('stroke', color);
      }

      // 🔴 双击删除（仅限非临时线）
      line.addEventListener('dblclick', function (e) {
        e.stopPropagation();
        const confirmed = confirm(`确定要删除线路 ${id} 吗？`);
        if (!confirmed) return;

        line.remove();
        this.lines = this.lines.filter(l => l.id !== id);
        this.statusText = `线路 ${id} 已删除`;
      });

      return line;
    },
    updateTransform() {

    },
    containerWheel(e) { // 中心底图缩放事件

      e.preventDefault();
      const scaleFactor = e.deltaY > 0 ? 0.9 : 1.1;
      const newScale = this.viewState.scale * scaleFactor;

      if (newScale < 0.3 || newScale > 10) return;

      const rect = this.container.getBoundingClientRect();
      const mouseX = e.clientX - rect.left;
      const mouseY = e.clientY - rect.top;

      this.viewState.x -= (mouseX - this.viewState.x) * (scaleFactor - 1);
      this.viewState.y -= (mouseY - this.viewState.y) * (scaleFactor - 1);
      this.viewState.scale = newScale;
    },
    svgContainerMousedown(e) { // 中心底图拖拽事件
      if (this.isAnnotating || e.target.classList.contains('line')) return;
      this.isDragging = true;
      this.lastX = e.clientX - this.viewState.x;
      this.lastY = e.clientY - this.viewState.y;
      this.svgCursor = 'grabbing';
    },
    resetView() { // 还原试图
      this.viewState = {x: 0, y: 0, scale: 1};
    },
    toggleAnnotationMode() { // 标注线路
      if (this.isAnnotating) {
        this.exitAnnotateMode();
      } else {
        this.enterAnnotateMode();
      }
    },
    exitAnnotateMode() { // 关闭标注模式
      if (!this.isAnnotating) return;
      this.isAnnotating = false;

      if (this.tempLine && this.tempLine.parentNode) {
        this.tempLine.remove();
        this.tempLine = null;
      }

      this.svgContainer.style.cursor = 'grab';
      this.statusText = '标注已结束';

      this.svgContainer.removeEventListener('click', this.handleAnnotateClick);
      this.svgContainer.removeEventListener('mousemove', this.handleMouseMove);
    },
    enterAnnotateMode() { // 进入标注模式
      if (this.isAnnotating) return;
      this.isAnnotating = true;
      this.startPoint = null;
      this.tempLine = null;

      this.svgCursor = 'crosshair';
      this.statusText = "请单击选择起点";

      this.svgContainer.addEventListener('click', this.handleAnnotateClick);
      this.svgContainer.addEventListener('mousemove', this.handleMouseMove);
    },
    handleAnnotateClick(e) { // 处理标注点击
      const point = this.screenToSvg(e.clientX, e.clientY);

      if (!this.startPoint) {
        this.startPoint = point;
        this.statusText = '已选择起点，请点击终点';

        this.tempLine = this.createLineElement('temp-line', point.x, point.y, point.x, point.y, 'blue', true);
        this.svgContainer.appendChild(this.tempLine);
      } else {
        const lineId = 'line_' + Date.now();
        const newLine = {
          id: lineId,
          x1: this.startPoint.x,
          y1: this.startPoint.y,
          x2: point.x,
          y2: point.y
        };

        const line = this.createLineElement(lineId, this.startPoint.x, this.startPoint.y, point.x, point.y, 'red');
        this.svgContainer.appendChild(line);
        this.lines.push(newLine);

        this.startPoint = null;
        this.tempLine.remove();
        this.tempLine = null;
        this.statusText = `线路 ${lineId} 已添加，可继续标注下一条`;

        this.handleAnnotateClickPost(newLine);
      }
    },
    handleMouseMove(e) { // 鼠标移动更新临时线
      if (!this.isAnnotating || !this.startPoint || !this.tempLine) return;
      const point = this.screenToSvg(e.clientX, e.clientY);
      this.tempLine.setAttribute('x2', point.x);
      this.tempLine.setAttribute('y2', point.y);
    },
    handleAnnotateClickPost(newLine){
      this.lineInfoDialogVisible = true;
      this.lineForm ={
        "createBy": "",
        "createTime": null,
        "updateBy": "",
        "updateTime": null,
        "remark": null,
        "deptId": 200,
        "drawingId": 1,
        "catenarySwitchId": -1,
        "lineName": "",
        "lineCode": newLine.id,
        "x1": newLine.x1,
        "y1": newLine.y1,
        "x2": newLine.x2,
        "y2": newLine.y2,
        "lineType": "TRACK",
        "isTrainPlaceable": "T",
        "standardParams": null,
        "customParams": null,
        "ext": null
      }
    },
    cancelLineForm(){
      this.lineInfoDialogVisible = false
    },
    submitLineForm(){
      this.$refs["lineForm"].validate(valid => {
        if (valid) {
          if (this.lineForm.id != null) {
            updateSingle_line_annotation(this.lineForm).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.lineInfoDialogVisible = false
              this.getSwitchAndLineList()
            })
          } else {
            addSingle_line_annotation(this.lineForm).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.lineInfoDialogVisible = false
              this.getSwitchAndLineList()
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
body {
  margin: 0;
  padding: 20px;
  font-family: Arial, sans-serif;
  overflow: hidden;
}

#container {
  width: 100%;
  height: 100vh;
  border: 1px solid #ccc;
  overflow: hidden;
  position: relative;
  touch-action: none;
}

#svg-container {
  width: 100%;
  height: 100%;
  cursor: grab;
  background-color: #f8f8f8;
}

#svg-container:active {
  cursor: grabbing;
}

.line {
  stroke-width: 4;
  stroke-dasharray: 5, 5;
  fill: none;
}

.line:hover {
  stroke-width: 8;
  stroke: aqua;
}

.temp {
  stroke: blue;
  stroke-dasharray: 4, 4;
}

.control-panel {
  margin-bottom: 10px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

button {
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
}

select, input {
  padding: 8px;
  font-size: 14px;
}

.status {
  font-size: 14px;
  color: #555;
  margin-left: auto;
}
</style>
